"""
自定义viewet
"""
from app.models import UserToken, User
from threedGestureProject.common import mixins, tools
from threedGestureProject.common.filter import MSearchFilter, MOrderingFilter
from threedGestureProject.common.pagination import CustomLimitOffsetPagination
from threedGestureProject.common.result import BaseResponse


class ModelViewSet(mixins.MCreateModelMixin,
                   mixins.MRetrieveModelMixin,
                   mixins.MUpdateModelMixin,
                   mixins.MDestroyModelMixin,
                   mixins.MListModelMixin):
    """
    提供默认 `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions 实现的类.
    """
    pass


class BaseViewSet(ModelViewSet):
    # 分页相关类
    pagination_class = CustomLimitOffsetPagination
    # 通用过滤后端，可用于过滤列表视图返回的结果。
    filter_backends = (MSearchFilter, MOrderingFilter)


user_token_queryset = UserToken.objects.all()


class TokenCreateModelMixin(mixins.MCreateModelMixin):

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            user_token = user_token_queryset.get(token=request.headers.get('Authorization'))
            current_user = user_token.user
            serializer.save(**{'creator': current_user})
        except User.DoesNotExist:
            serializer.save()
        headers = self.get_success_headers(serializer.data)
        return BaseResponse(data=serializer.data, headers=headers)


class TokenUpdateModelMixin(mixins.MUpdateModelMixin):

    def update(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        try:
            user_token = user_token_queryset.get(token=request.headers.get('Authorization'))
            current_user = user_token.user
            serializer.save(**{'modified': current_user, 'modified_time': tools.now()})
        except User.DoesNotExist:
            serializer.save()
        return BaseResponse(data=serializer.data)


class TokenViewSet(TokenCreateModelMixin,
                   TokenUpdateModelMixin,
                   BaseViewSet):
    pass
